/* Copyright (C) 2014-2015 Mammoth Inc. */

var m = new M("mm_volumes");

$(document).ready(function() {
	var _Data = [];
	
	var _loadVolumeCard = function(data) {
		var _rate = '',_limit = '', _btn = '';
		if(data.percent == undefined) {
			_btn = '<button type="button" class="mm_learnButton">开始学习</button>';
			_rate = '<p class="learnedPeople">(已有 <span>' + data.learnNum + '</span> 人学习)</p>';
		} else {
			_btn = '<button type="button" class="mm_learnButton">继续学习</button>';
			_rate = '<div class="progress"><div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="' + data.percent + '" aria-valuemin="0" aria-valuemax="100" style="width: '+data.percent+'%;"></div></div><p class="progress-text">已学<span>'+data.percent+'</span>%</p>'
		}
		if(data.limit == "0") {
			_limit = '<img src="http://s.mengma.com/img/limitedfree.svg" style="width:40px;height:auto;position:absolute;left:240px;top:-1px;"/>'
		} 
		var _t = '<div class="col-sm-6 col-md-4 col-lg-3 mm_volumes_card" data-log=""><a href= "'+data.jumpurl+'" class="learn"><div class="front">\
			<div class="mm_mask"></div><img class="mm_volumns_icon" src="'+data.img+'" /><p class="mm_volumeName">'+data.title+'</p>'+_rate + _limit +'</div><div class="back"><p class="mm_volumeTitle">'+data.title+'</p><div class="description"><p id="clamp-text">' + data.description + '</p></div>'+_btn+'</div></a></div>'
		return _t;
	}
	var finishLesson = function(img, title, jumpurl) {
		var _t = '<div class="mm_learned_card"><img src="'+img+'" /><p>'+title+'</p><a href="'+jumpurl+'" class="mm_learnedButton">温故知新</a></div>';
		$(".mm_bottom_content").append(_t);
	}
	var loadCalendar = function(year, month, type) {
		$("#mm_date").html(year + "年" + month + "月");
		date = year + "-" + month;
		$.ajax({
			url:"http://api.mengma.com/User/calendar/33",
			type:"GET",
			dataType: "json",
			data: {
				start: date,
				type: type 
			},
			xhrFields: {
				withCredentials: true
			},
			success: function(data) {
				
				$(".mm_month_main").html("");
				if(data) {
					var _d = '';
					$("#continuLearn").html(data.continuLearn);
					$("#learnSum").html(data.learnSum);
					_d = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>'
					
					for(var z = 0; z < parseInt(data.week_num); z++) {
						_d += '<span>&nbsp;</span>'
					}
					for(var i = 0; i < data.data.length; i++) {
						if(data.data[i].status == 0) {
							if(data.data[i].current == 1) {
								_d += '<span class="today" data-toggle="tooltip" data-placement="bottom" data-html="true" title="什么都没做<br />'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							} else {
								_d += '<span data-toggle="tooltip" data-placement="bottom" data-html="true" title="什么都没做<br />'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							}
						} else if(data.data[i].status == 1) {
							if(data.data[i].current == 1) {
								_d += '<span class="data_1 today" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							} else {
								_d += '<span class="data_1" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							}
						} else if(data.data[i].status == 2) {
							if(data.data[i].current == 1) {
								_d += '<span class="data_2 today" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							} else {
								_d += '<span class="data_2" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							}
						} else {
							if(data.data[i].current == 1) {
								_d += '<span class="data_3" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							} else {
								_d += '<span class="data_3" data-toggle="tooltip" data-placement="bottom" data-html="true" title="'+data.data[i].content+'">'+(parseInt(i)+1)+'</span>';
							}
						}
					}
					$(".mm_month_main").html(_d);
					$('[data-toggle="tooltip"]').tooltip();
				}
				
			}
		});
	}
	var learningLesson = function(data) {
		var _top = '';
		if(data.length > 0) {
			for(var i = 0; i < data.length; i++) {
				var _b = '', middle_center_style = '';
				var _medalCard = '', _link = '', _medal = '', _chapterUrl = '';
				if(data[i].medal != undefined) {
					for(var j = 0; j < data[i].medal.length; j++) {
						if(data[i].medal[j].usermedal) {
							_medal += '<li><img src="'+data[i].medal[j].img+'" alt="medal"></li>';
						} else {
							_medal += '<li><img src="'+data[i].medal[j].img+'" alt="medal"><em></em></li>';
						}
					}
					if(i == 0) {
						wid = data[i].medal.length * 80;
					} else {
						wid = data[i].medal.length * 54;
					}
					_medalCard = '<ul class="mm_top_medal" style="width:'+wid+'px">'+_medal+'</ul>';
				} else {
					middle_center_style = 'style="margin-top: 40px;"';
				}
				if(data[i].newold == 0) {
					_link = 'http://www.mengma.com/class/lesson/'+data[i].study+'/'+data[i].ctype;
					_chapterUrl = 'http://www.mengma.com/class/course/'+data[i].vid;
				} else {
					if(data[i].lang == 6) {
						_link = 'http://s.mengma.com/frontEnd/#/'+data[i].study+'/0';
						_chapterUrl = 'http://s.mengma.com/frontEnd/#/' + data[i].vid;
					} else if(data[i].lang == 8) {
						_link = 'http://s.mengma.com/javascript/#/'+data[i].study+'/0';
						_chapterUrl = 'http://s.mengma.com/javascript/#/' + data[i].vid;
					}
				}
				
				if(i == 0) {
					_top = '<a href="' + _chapterUrl + '"><img class="mm_volumns_icon" src="'+data[i].img+'"><p class="mm_volumeName">'+data[i].title+'</p></a>\
						<div style="width:540px;margin:0 auto;">\
							<div class="progress" style="width:500px;float:left;margin-top:5px;"><div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="'+data[i].percent+'" aria-valuemin="0" aria-valuemax="100" style="width:'+data[i].percent+'%;"></div></div><div>'+data[i].percent+'%</div>\
						</div>\
						<p class="progress-text">上次学习时间 '+data[i].time+'</p><a href="'+_link+'" class="mm_learnButton">继续学习</a>\
						'+_medalCard;
					$(".mm_top_content").html(_top);
				} else {
					_b = '<div class="mm_mylesson_card">\
							<div class="mm_middle_left"><a href="' + _chapterUrl + '"><img src="'+data[i].img+'" /><p>'+data[i].title+'</p></a></div>\
							<div class="mm_middle_center" '+middle_center_style+'><div style="width:540px;margin:0 auto;">\
								<div class="progress" style="width:500px;float:left;margin-top:5px;">\
									<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="'+data[i].percent+'" aria-valuemin="0" aria-valuemax="100" style="width: '+data[i].percent+'%;"></div>\
								</div><div>'+data[i].percent+'%</div></div><p class="progress-text">上次学习时间 '+data[i].time+'</p>'+_medalCard+'</div>\
							<div class="mm_middle_right"><a href="'+_link+'" class="mm_learnButton">继续学习</a></div>\
						</div>';
					$(".mm_mylesson_middle").append(_b);
				}
			}
		}
	}
	var cardSortAndLayout = function(sortKey, dir) {
		$(".mm_volumes_card").sort(function(a, b) {
			if (dir) {
				return $(a).data(sortKey) - $(b).data(sortKey) ;
			} else {
				return $(b).data(sortKey) - $(a).data(sortKey) ;
			}
		}).remove().map(function() {
			$(".mm_transition").eq(0).append($(this));
		});
	};
	var allLesson = function() {
		//MYLESSON
		$.ajax({
			url:"http://api.mengma.com/volume/record/33",
			type:"GET",
			dataType: "json",
			xhrFields: {
				withCredentials: true
			},
			success: function(data) {
				if(data) {
					if(data.finish == null) {
						$(".mm_mylesson_bottom").css("display","none");
					} else {
						if(data.finish.length > 0) {
							$(".mm_mylesson_bottom").html('<div class="mm_top_title">已学完</div><div class="mm_bottom_content"></div>');
							for(var j = 0; j < data.finish.length; j++) {
								finishLesson(data.finish[j].img, data.finish[j].title, data.finish[j].jumpurl);
							}
						}
					}
					if(data.studying.length == 0 || data.studying == null) {
						var _template = '<div class="mm_top_none"><p class="face">:(</p><p>您还没有学习过课程</p><p>赶快到“全部课程”里挑一门课程，小试身手吧~</p></div>'
						$(".mm_top_content").html(_template);
					} else {
						learningLesson(data.studying);
						setTimeout(function() {
							for(var i = 0; i < $(".mm_mylesson_card").length; i++) {
								if($(".mm_middle_left").eq(i).height() > 100) {
									$(".mm_middle_right").eq(i).css("margin-top","30px");
									if($(".mm_middle_center").eq(i).height() == 47) {
										$(".mm_middle_center").eq(i).css("margin-top","50px");
									}
								} else {
									$(".mm_middle_right").eq(i).css("margin-top","15px");
								}
								$(".mm_mylesson_card").eq(i).height($(".mm_middle_left").eq(i).height());
							}
						},500)
						
					}
				}
			}
		});
		var date = new Date();
		var year = date.getFullYear(); 
		var month = date.getMonth()+1;
		loadCalendar(year, month, 1);//1 是月2 是周
		$("#mm_last").click(function() {
			if(month > 1) {
				month = month - 1;
				loadCalendar(year, month, 1);
			} else {
				year = year - 1;
				month = 13;
			}
		});
		$("#mm_next").click(function() {
			if(month < 12) {
				month = month + 1;
				loadCalendar(year, month, 1);
			} else {
				year = year + 1;
				month = 0;
			}
		});
		
		$("#mm_mylearn_month").click(function() {
			$(this).addClass("active");
			$("#mm_mylearn_week").removeClass("active");
			$(".mm_month_main").css("display","block");
			$(".mm_week_main").css("display","none");
			date = new Date();
			year = date.getFullYear(); 
			month = date.getMonth()+1;
			loadCalendar(year, month, 1);
		});
		//ALL and NEW
		$.ajax({
			url: "http://api.mengma.com/volume/newest/33",
			type: "GET",
			dataType: "json",
			xhrFields: {
				withCredentials: true
			},
			success: function(data) {
				_Data = data;
				//All Lesson
				var _tempLate1 = '', _a = '<p class="mm_newUserTitle" style="margin-top:0;">大多数初学编程的同学，都从这门课程开始</p>', _b = '<p class="mm_newUserTitle">还有很多同学，是为了来找这些课程</p>', _c = '<p class="mm_newUserTitle">对于有一定编程基础的同学，我们也提供了以下课程</p>', _d = '';
				for(var i = 0; i < _Data.length; i++) {
					if(_Data[i].vid == "66") {
						_a += _loadVolumeCard(_Data[i]);
					} else if(_Data[i].vid == "69") {
						_b += _loadVolumeCard(_Data[i]);
					} else if(_Data[i].vid == "45") {
						_b += _loadVolumeCard(_Data[i]);
					} else if(_Data[i].vid == "88") {
						_b += _loadVolumeCard(_Data[i]);
					} else {
						_c += _loadVolumeCard(_Data[i]);
					}
				}
				// _a += ''
				// _b += ''
				// _c += ''
				_d = '<p class="mm_newUserTitle">没有想要的？点击图标，程序员蜀黍帮你量身打造</p><div class="col-sm-6 col-md-4 col-lg-3 mm_volumes_card" data-id="17612" data-new="38" data-log="">\
					<a href="http://www.mengma.com/x/" class="learn x">\
						<div class="mm_x">\
							<div class="mm_mask"></div>\
							<img class="mm_volumns_icon" src="http://s.mengma.com/img/mm_class/x.png">\
							<p class="mm_volumeName">x课程</p>\
						<div>\
					</a>\
				</div>';
				_tempLate1 = '<div class="mm_list mm_transition"><div class="col-md-12"><div class="row">'+_a+'</div><div class="row" style="width:80%;margin:0 auto;">'+_b+'</div><div class="row" style="max-width:1474px">'+_c+'</div><div class="row">'+_d+'</div></div></div>';
				$(".mm_list_wrapper").eq(1).html(_tempLate1);

				//NEW LESSON
				var _tempLate2 = '';
				for(var j = 0; j < _Data.length; j++) {
					_tempLate2 += _loadVolumeCard(_Data[j]);
				}

				$(".mm_list_wrapper").eq(2).css('max-width','1474px').html(_tempLate2);
			}
		});
		//HOT LESSON
		$.ajax({
			url: "http://api.mengma.com/volume/hot/33",
			type: "GET",
			dataType: "json",
			xhrFields: {
				withCredentials: true
			},
			success: function(data) {
				var _tempLate3 = '';
				for(var z = 0; z < data.length; z++) {
					_tempLate3 += _loadVolumeCard(data[z]);
				}
				$(".mm_list_wrapper").eq(3).css('max-width','1474px').html(_tempLate3);
			}
		});
		$("#mm_mylearn_week").click(function() {
			$(this).addClass("active");
			$("#mm_mylearn_month").removeClass("active");
			$(".mm_month_main").css("display","none");
			$(".mm_week_main").css("display","block");
			loadCalendar(year, month, 2);
			var myChart = echarts.init(document.getElementById('main'));
			$.ajax({
				url:"http://api.mengma.com/User/calendar/33",
				type:"GET",
				dataType: "json",
				data: {
					type: 2
				},
				xhrFields: {
					withCredentials: true
				},
				success: function(data) {
					var statArr = [], weekArr = [];
					for(var i = 0; i < data.data.length; i++) {
						if(data.data[i].status == 0) {
							data.data[i].content = "什么都没干<br />" + data.data[i].content;
						}
						statArr.push(data.data[i].status);
						weekArr.push("周"+data.data[i].week);
					}
					option = {
						tooltip : {
							trigger: 'item',
							formatter: function(params,ticket,callback) {
								for(var j = 0; j < weekArr.length; j++) {
									if(params.name == weekArr[j]) {
										return data.data[j].content;
									}
								}
							}
						},
						calculable : false,
						xAxis : [
							{
								type : 'category',
								boundaryGap : false,
								data : weekArr,
								axisLine: {
									lineStyle: {color: 'rgba(0,0,0,.3)'}
								}
							}
						],
						yAxis : [
							{
								type : 'value',
								splitNumber: 3,
								axisLine: {
									lineStyle: {color: 'rgba(0,0,0,.3'}
								}
							}
						],   //横纵坐标
						series : [
							{
								name:'活跃度',
								type:'line',
								smooth:true,
								itemStyle: {
									normal: {
										areaStyle: {
											type: 'default',
											color: 'rgba(255, 168, 75, .5)'
										},
										color: '#ffa84b'
									}
								},
								data: statArr
							}
						]
					};
					// 为echarts对象加载数据
					myChart.setOption(option);
				}
			});
		});
	}

	$('body').css('overflow-x','hidden');
	var _transitions = $(".mm_transition");
	var _list_wrapper = $(".mm_list_wrapper");
	$(".mm_volumes_card").each(function(index) {
		$clamp($(this).find("#clamp-text")[0], {
			clamp: 5
		});
	});
	if(!$("#mm_classlist").data('new')) {
		$(".mm_list").eq(0).css('display','block');
	}
	
	var link = window.location.href;
	if(link.indexOf('?') != -1) {
		$('.mm_list_wrapper').eq(1).css({
			'display':'block',
			'padding-top':'140px'
		});
		// $(".mm_volumes_selector").find("li").eq(1).addClass("active").siblings().removeClass("active");
	}
	// var l = $(".mm_volumes_card").eq(0).offset().left + 15;
	// $('.mm_volumes_selector').css('left', l + 'px');
	// $('.mm_volumes_selector').css('right', l + 'px');
	var m =	($(document).width() - $(".mm_volumes_selector").width())/2 - 24;
		$(".mm_volumes_selector").css("margin-left",m);
	$(window).resize(function() {
	// var l = $(".mm_volumes_card").eq(0).offset().left + 15;
	// $('.mm_volumes_selector').css('left', l + 'px');
	// $('.mm_volumes_selector').css('right', l + 'px');
		var m =	($(document).width() - $(".mm_volumes_selector").width())/2 - 10;
		$(".mm_volumes_selector").css("margin-left",m);
	});
	
	
	$(".mm_volumes_selector").find("li").click(function() {
		$(this).addClass("active").siblings().removeClass("active");
		var id = $(this).data("id");
		for(var i = 0; i < _list_wrapper.length; i++) {
			_list_wrapper.eq(i).css("display","none");
		}
		_list_wrapper.eq(id).css("display","block");
	});
	if($(".mm_user").length == "0") {
		$(".mm_volumes_selector").find("li").eq(0).remove();
	}
	$(".mm_volumes_selector").find("li").eq(0).click();
	allLesson();
	
	
});